package com.itheima.mp.domain.dto;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@ApiModel(description = "返回分页数据")
public class PageDto<T> {
    @ApiModelProperty("总条数")
    private Long total;
    @ApiModelProperty("总页数")
    private Long pages;
    @ApiModelProperty("集合")
    private List<T> list;

    public static <po,vo> PageDto<vo> ToPageDto(Page<po> p, Class<vo> clazz){
        PageDto<vo> dto = new PageDto<>();
        dto.setTotal(p.getTotal());
        dto.setPages(p.getPages());
        //获取user列表
        List<po> pos = p.getRecords();
        if(CollUtil.isEmpty(pos)){
            return dto;
        }
        dto.setList(BeanUtil.copyToList(pos,clazz));
        //4.返回
        return dto;
    }

    public static <po,vo> PageDto<vo> pageDto(Page<po> p, Function<po,vo> function){
        PageDto<vo> dto = new PageDto<>();
        dto.setTotal(p.getTotal());
        dto.setPages(p.getPages());
        //获取user列表
        List<po> pos = p.getRecords();
        if(CollUtil.isEmpty(pos)){
            return dto;
        }
        dto.setList(pos.stream().map(function).collect(Collectors.toList()));
        //4.返回
        return dto;
    }
}
